package com.cultusoft.groovin.plugins.fitnesse;

import com.cultusoft.groovin.plugins.build.ProjectClasspathCreator
import com.cultusoft.groovin.plugins.project.LibraryProject
import com.cultusoft.groovin.log.GroovinLogger
import com.cultusoft.groovin.configuration.Configuration
import com.cultusoft.groovin.plugins.build.ProjectDependencyDownloader
import com.cultusoft.groovin.script.GroovinProperties


class FitServerRunner {
    def neededPackages = [new LibraryProject(group:"org/fitnesse", id:"fitnesse", version:"20060719") ,
                            new LibraryProject(group:"org/fitnesse", id:"fitlibrary", version:"20060719")] as List

    def logger = new GroovinLogger(this)

    def host
    def port
    def socketTicket
	
 	public void run() {
        def args = GroovinProperties.args

        if (args.size() != 3) {
            throw new RuntimeException("FitServerRunner needs three arguments to be passed to it. The host, the port, and the socketTicket")
        }

        host = args[0]
        port = args[1]
        socketTicket = args[2]

		runFitnesseTest()
 	}

	private void runFitnesseTest() {
        def configuration = new Configuration()
		def fitnesseProperties = configuration.getFitnesseProperties()
		
		def myClasspath = new ProjectClasspathCreator().createClasspathFromProjects(configuration.getProjects())
		
		File fitnesseReportFolder = new File(fitnesseProperties.logDirectory)
		
		if (!fitnesseReportFolder.exists()) {
		    fitnesseReportFolder.mkdir()		    
		}
		
		def testOutputFilePath = new File(fitnesseReportFolder, "fitnesse_run_with_socket_ticket_$socketTicket" + ".log").getPath()
        logger.debug "using classpath $myClasspath"
        logger.debug "running tests using host $host port $port socketTicket $socketTicket"
		logger.log "Test output will be saved to $testOutputFilePath"
		
		def ant = new AntBuilder()
		ant.java( classname:"fit.FitServer",
				classpath:myClasspath,
				resultproperty:"returnCode",
				failonerror:true,
				fork:true,
				output:testOutputFilePath
				) {

			arg(value:host)
			arg(value:port)
			arg(value:socketTicket)
		}
		
/*
		def returnCode = ant.properties.antProject.getProperty("returnCode")
		
		if (!returnCode.equals("0")) {
			throw new Exception ("Fitnesse tests have failed.")
		} else {
			logger.log("Fitnesse tests have passed")
		}
*/
        logger.log "Fished running this test"
	
 	}

}
